package com.robot.thread;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 * User: li
 * Date: 2019/12/8
 * Time: 9:43
 * PROJECT：robot
 * PACKAGE: com.robot
 *
 * @author:55324936@qq.com To change this template use File | Settings | File Templates.
 */
@Configuration
public class ThreadPoolConfig {

    @Value("${core.pool.size}")
    private int corePoolSize;
    @Value("${max.pool.size}")
    private int maxPoolSize;
    @Value("${queue.capacity}")
    private int queueCapacity;

    @Bean
    public ThreadPoolTaskExecutor taskPool(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        /**核心线程数**/
        executor.setCorePoolSize(corePoolSize);
        /**最大线程数**/
        executor.setMaxPoolSize(maxPoolSize);
        /**队列容量**/
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("runTest-");
        /**
         * 最大线程数10个，当pool已经达到max size的时候，如何处理新的任务
         * caller-runs:不在新创建线程，而是在调用者所以在的线程来执行
         * **/
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    @Bean
    public ThreadPoolTaskScheduler init(){
        return new ThreadPoolTaskScheduler();
    }
}
